package com.qf.service.impl;

import com.qf.DBUtil.RandomUtils;
import com.qf.dao.AddressDao;
import com.qf.dao.CartDao;
import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailsDao;
import com.qf.pojo.Cart;
import com.qf.pojo.Order;
import com.qf.pojo.OrderDetailNew;
import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.service.impl
 * @Description:
 * @Date 2022/10/3 19:32
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;
    @Autowired
    CartDao cartDao;
    @Autowired
    OrderDetailsDao orderDetailsDao;
    @Autowired
    AddressDao addressDao;
    @Override
    public List<Order> findOrder() {
        return null;
    }

    @Override
    public List<Order> findAllOrder(int id) {
        List<Order> orderList = orderDao.getOrderList(id);
        for (Order order : orderList) {
            order.setAddress(addressDao.findByOrderAId(order.getAid()).getDetail());
        }
        return orderList;
    }

    @Override
    public Order addOrder(int id, Integer aid) {
        Order order = new Order();
        List<Cart> cartList = cartDao.getCardById(id);
        int sum = 0;
        for (Cart cart : cartList) {
            sum += cart.getMoney();
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = format.format(date);
        String active = RandomUtils.createActive();
        order.setId(active);
        order.setUid(id);
        order.setMoney(sum);
        order.setStatus("1");
        order.setTime(time);
        order.setAid(aid);
        orderDao.insert(order);

        for (Cart cart : cartList) {
            OrderDetailNew orderDetail = new OrderDetailNew();
            orderDetail.setOid(active);
            orderDetail.setPid(cart.getPid());
            orderDetail.setNum(cart.getNum());
            orderDetail.setMoney(cart.getMoney());
            orderDetailsDao.insert(orderDetail);
        }
        cartDao.clearCart(id);
        return order;
    }
}
